package draft;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.Timer;

import test.TestMinimax;
import ui.AvailablePlayerPanel;
import ui.DraftClient;
import ui.TeamPanel;


/**
 * FantasyManager.java
 * 
 * 
 * 
 * @author Doug Hyde, hyde@wustl.edu
 */

public class FantasyManager {

	// Model
	public static League league;	// Actual league
	public static ArrayList<Player> players;
	
	private static int turn = 0;		// Team ID of current turn
	private static int user;
	private static boolean forward = true;
	
	// Algorithm
	private static Minimax algo;
	
	// User Interface
	public static DraftClient client;
	
	
	// Constants
	public static final int NUM_PICKS = 10;

	static int timeCount = 0;
	static Timer timer = new Timer(1000, new ActionListener() {
          public void actionPerformed(ActionEvent e) {
              timeCount++;
          }
       });
	
	
	public FantasyManager (int size, int userOrder) {
		League.size = size;
		players = TestMinimax.randomPlayers(300);  // TODO Ratings.collectRatings() );
		league = new League();
		user = userOrder;
		algo = new Minimax();
	
	}
	
	public void initiate(){
		if (user == 0){
			userTurn();
		}
	}
	
	public static int currentTeam () {
		return turn;
	}
	
	public static int userTeam () {
		return user;
	}
	
	
	public static void userTurn () {
//		while(client == null){
//			//this is necessary for when the user has the first pick overall and draft client is not yet loaded
//		}
		client.setEnabled(false);
		client.setMainLabel("Minimax algorithm computing best draft choice, stand by...");
		Player pick = algo.search(user);
		client.setMainLabel("Minimax algorithm selected " + pick.name);
		recordTurn(pick);
		timer.start();
		while(timeCount < 5){
			
		}
		timer.stop();
		timeCount = 0;
		client.setMainLabel("Input Opponent Draft Pick");
		client.setEnabled(true);
	}
	
	
	public static void receiveTurn (Player p) {
		// Store drafted player
		recordTurn(p);
		
		// Test if draft is over
		if (league.movesLeft <= 0) {
			System.out.println("DRAFT IS OVER"); // TODO show alert
			return;
		}
			
		// Run user's turn if necessary
		if (turn == user) {
			userTurn();
		}
	}
	
	
	private static void recordTurn (Player p) {
		System.out.println("Team "+turn+": " + p);
		Minimax.addPlayer(p, turn);
		league.addPlayer(p, turn);
		players.remove(p);
		AvailablePlayerPanel.removePlayer(p);
		nextTurn();
	}
	
	
	
	private static void nextTurn () {
		System.out.println(league);
		if (forward) {
			if (turn == League.size - 1) {
				forward = false;
			} else {
				++turn;
			}
		} else {
			if (turn == 0) {
				forward = true;
			} else {
				--turn;
			}
		}
		
		TeamPanel.setVisibleTeamTab(turn);
		if(user == turn){
			userTurn();
		}
	}
	
	
	public static void main(String[] args) {
		client = new DraftClient();
		client.manager.initiate();
	}
}
